
import 'package:device_info_plus/device_info_plus.dart';
import 'package:dio/dio.dart';
import 'package:earclean/app/request/http_config.dart';
import 'package:earclean/app/request/request_main.dart';
import 'package:earclean/app/request/result_data.dart';
import 'package:earclean/app/util/common_utils.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart' as getx;
import 'package:package_info_plus/package_info_plus.dart';

import '../routes/app_pages.dart';


class HttpRequest {
  static final BaseOptions options = BaseOptions(
      //  baseUrl: HTTPConfig.baseURL,
      connectTimeout: Duration(milliseconds: HTTPConfig.timeout));
  static final Dio dio = Dio(options);

  static Future<ResultData> _request<T>(String url,
      {String method = 'get', dynamic params, Interceptor? inter}) async {
    final options = Options(method: method);

    final Interceptor dInter =
        InterceptorsWrapper(onRequest: (options, handler) async {
      print("拦截了请求");
      print(options.baseUrl + options.path);
      print(params);

      return handler.next(options);
    });

    List<Interceptor> inters = [dInter];
    if (inter != null) {
      inters.add(inter);
    }
    //统一添加拦截器中
    dio.interceptors.clear();
    dio.interceptors.addAll(inters);

    try {
      Response response;
      if (method == 'get') {
        response =
            await dio.request(url, queryParameters: params, options: options);
      } else {
        response = await dio.request(url, data: params, options: options);
      }

      if (response.statusCode != 200) {
        if (response.data['code'] == 401) {
          // 请重新登录
          Map? m = await RequestMain.postUrl({});
          if (m.isNotEmpty && m['code'].toString() == "200") {
            EasyLoading.showToast('请重新登录');
            await box.remove('key');
            await box.remove('kefu');
            await box.remove('tab');
            getx.Get.offAllNamed(Routes.LOGIN);
          }
        }
        return ResultData(response.data, false, response.statusCode);
      }
      return ResultData(response.data, true, response.statusCode);
    } on DioError catch (e) {
      // 请求错误处理
      Response? errorResponse;
      if (e.response != null) {
        errorResponse = e.response;
      } else {
        errorResponse =
            Response(statusCode: 666, requestOptions: RequestOptions(path: '网络连接失败'));
      }
      return ResultData(
        errorResponse!.data,
        false,
        errorResponse.statusCode,
      );
    }
  }

  //get请求
  static Future<ResultData> get<T>(
    String url, {
    Map<String, dynamic>? params, //请求参数
    Interceptor? inter, //自定义拦截器
  }) {
    return HttpRequest._request(url,
        method: "get", params: params, inter: inter);
  }

  //post 请求
  static Future<ResultData> post<T>(
    String url, {
    Map<String, dynamic>? params, //请求参数
    Interceptor? inter, //自定义拦截器
  }) {
    return HttpRequest._request(url,
        method: "post", params: params, inter: inter);
  }

  //post 请求
  static Future<ResultData> upLoadFile<T>(
    String url, {
    Map<String, dynamic>? params, //请求参数
    Interceptor? inter, //自定义拦截器
  }) {
    return HttpRequest._request(url,
        method: "post", params: params, inter: inter);
  }
  // TODO：- 上传文件
}
